#!/usr/bin/env python3
"""
GPU加速组件
包含GPU加速选项和硬件选择功能
"""

from PyQt6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QLabel, 
                             QCheckBox, QComboBox, QFrame, QGroupBox)
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QFont

from hardware_detector import hardware_detector


class HardwareOptionWidget(QWidget):
    """单个硬件选项组件"""
    
    def __init__(self, hardware_type: str, parent=None):
        super().__init__(parent)
        self.hardware_type = hardware_type
        self.hardware_info = {}
        self.init_ui()
        self.update_hardware_info()
    
    def init_ui(self):
        """初始化UI"""
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(8)
        
        # 硬件选择复选框
        self.checkbox = QCheckBox()
        self.checkbox.setStyleSheet("""
            QCheckBox {
                spacing: 6px;
                font-family: 'Microsoft YaHei', Arial, sans-serif;
                font-size: 10px;
                color: #2c3e50;
            }
            QCheckBox::indicator {
                width: 14px;
                height: 14px;
            }
            QCheckBox::indicator:unchecked {
                border: 2px solid #bdc3c7;
                border-radius: 2px;
                background-color: white;
            }
            QCheckBox::indicator:checked {
                border: 2px solid #3498db;
                border-radius: 2px;
                background-color: #3498db;
            }
        """)
        layout.addWidget(self.checkbox)
        
        # 硬件标签（紧凑显示）
        self.label = QLabel()
        self.label.setFont(QFont("Microsoft YaHei", 9))
        self.label.setStyleSheet("color: #2c3e50; min-width: 80px; max-width: 80px;")
        layout.addWidget(self.label)
        
        # 任务数选择（紧凑布局）
        task_layout = QHBoxLayout()
        task_layout.setSpacing(3)
        
        task_label = QLabel("任务：")
        task_label.setFont(QFont("Microsoft YaHei", 8))
        task_label.setStyleSheet("color: #2c3e50;")
        task_layout.addWidget(task_label)
        
        self.task_combo = QComboBox()
        self.task_combo.addItems([str(i) for i in range(1, 10)])
        self.task_combo.setStyleSheet("""
            QComboBox {
                border: 1px solid #bdc3c7;
                border-radius: 2px;
                padding: 2px;
                background-color: #ecf0f1;
                color: #2c3e50;
                font-family: 'Microsoft YaHei', Arial, sans-serif;
                font-size: 9px;
                min-width: 40px;
                max-width: 40px;
            }
            QComboBox:disabled {
                background-color: #f8f9fa;
                color: #bdc3c7;
            }
            QComboBox QAbstractItemView {
                background-color: white;
                color: #2c3e50;
                selection-background-color: #3498db;
            }
        """)
        task_layout.addWidget(self.task_combo)
        
        layout.addLayout(task_layout)
        
        self.setLayout(layout)
        
        # 连接信号
        self.checkbox.stateChanged.connect(self.on_checkbox_changed)
    
    def update_hardware_info(self):
        """更新硬件信息"""
        if self.hardware_type == "cpu":
            self.hardware_info = hardware_detector.get_cpu_info()
            self.label.setText("CPU转码")
            self.checkbox.setChecked(False)  # CPU默认不选
            self.task_combo.setCurrentText("1")  # CPU默认1个任务
            
        elif self.hardware_type == "integrated":
            # 使用存在性检测
            if hardware_detector.has_integrated_gpu():
                gpus = hardware_detector.get_integrated_gpu_info()
                self.hardware_info = gpus[0] if gpus else {}
                self.label.setText("集显转码")
                self.checkbox.setChecked(True)  # 集显默认选择
                self.task_combo.setCurrentText("2")  # 集显默认2个任务
            else:
                self.hardware_info = {}
                self.label.setText("集显转码")
                self.checkbox.setChecked(False)
                self.checkbox.setEnabled(False)
                
        elif self.hardware_type == "dedicated":
            # 使用存在性检测
            if hardware_detector.has_dedicated_gpu():
                gpus = hardware_detector.get_dedicated_gpu_info()
                self.hardware_info = gpus[0] if gpus else {}
                self.label.setText("独显转码")
                self.checkbox.setChecked(True)  # 独显默认选择
                self.task_combo.setCurrentText("3")  # 独显默认3个任务
            else:
                self.hardware_info = {}
                self.label.setText("独显转码")
                self.checkbox.setChecked(False)
                self.checkbox.setEnabled(False)
        
        # 初始状态设置
        self.on_checkbox_changed()
    
    def on_checkbox_changed(self):
        """复选框状态改变时的处理"""
        is_checked = self.checkbox.isChecked()
        self.task_combo.setEnabled(is_checked)
    
    def is_selected(self) -> bool:
        """是否被选中"""
        return self.checkbox.isChecked() and self.checkbox.isEnabled()
    
    def get_task_count(self) -> int:
        """获取任务数"""
        if self.is_selected():
            return int(self.task_combo.currentText())
        return 0
    
    def get_hardware_info(self) -> dict:
        """获取硬件信息"""
        return self.hardware_info


class GPUAccelerationWidget(QWidget):
    """编码硬件选择组件"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.init_ui()
    
    def init_ui(self):
        """初始化UI"""
        # 主布局
        main_layout = QVBoxLayout()
        main_layout.setSpacing(8)
        
        # 标题
        title_label = QLabel("⚡ 选择编码硬件")
        title_label.setFont(QFont("Microsoft YaHei", 12, QFont.Weight.Bold))
        title_label.setStyleSheet("color: #2c3e50; margin-bottom: 8px;")
        main_layout.addWidget(title_label)
        
        # 硬件选项容器
        self.hardware_container = QFrame()
        self.hardware_container.setFrameShape(QFrame.Shape.StyledPanel)
        self.hardware_container.setStyleSheet("""
            QFrame {
                background-color: #f8f9fa;
                border: 1px solid #e9ecef;
                border-radius: 6px;
                padding: 12px;
            }
        """)
        
        # 硬件选项水平布局
        hardware_layout = QHBoxLayout()
        hardware_layout.setSpacing(20)
        hardware_layout.setContentsMargins(10, 5, 10, 5)
        
        # 创建硬件选项组件
        self.cpu_widget = HardwareOptionWidget("cpu", self)
        self.integrated_widget = HardwareOptionWidget("integrated", self)
        self.dedicated_widget = HardwareOptionWidget("dedicated", self)
        
        # 添加硬件选项到水平布局
        hardware_layout.addWidget(self.cpu_widget)
        hardware_layout.addWidget(self.integrated_widget)
        hardware_layout.addWidget(self.dedicated_widget)
        hardware_layout.addStretch()
        
        self.hardware_container.setLayout(hardware_layout)
        main_layout.addWidget(self.hardware_container)
        
        self.setLayout(main_layout)
    
    def get_acceleration_settings(self) -> dict:
        """获取加速设置"""
        settings = {
            "gpu_acceleration_enabled": True,  # 现在默认启用GPU加速
            "cpu": {
                "enabled": self.cpu_widget.is_selected(),
                "task_count": self.cpu_widget.get_task_count(),
                "info": self.cpu_widget.get_hardware_info()
            },
            "integrated_gpu": {
                "enabled": self.integrated_widget.is_selected(),
                "task_count": self.integrated_widget.get_task_count(),
                "info": self.integrated_widget.get_hardware_info()
            },
            "dedicated_gpu": {
                "enabled": self.dedicated_widget.is_selected(),
                "task_count": self.dedicated_widget.get_task_count(),
                "info": self.dedicated_widget.get_hardware_info()
            }
        }
        
        # 计算总任务数
        total_tasks = 0
        for hardware in ["cpu", "integrated_gpu", "dedicated_gpu"]:
            if settings[hardware]["enabled"]:
                total_tasks += settings[hardware]["task_count"]
        
        settings["total_parallel_tasks"] = total_tasks
        
        return settings
    
    def is_gpu_acceleration_enabled(self) -> bool:
        """GPU加速是否启用"""
        return self.gpu_checkbox.isChecked()
    
    def has_selected_hardware(self) -> bool:
        """是否有选中的硬件"""
        if not self.is_gpu_acceleration_enabled():
            return True  # 如果GPU加速关闭，则认为有硬件（使用CPU）
        
        return (self.cpu_widget.is_selected() or 
                self.integrated_widget.is_selected() or 
                self.dedicated_widget.is_selected())
    
    def reset_settings(self):
        """重置GPU加速设置到默认状态"""
        # 重置GPU加速开关
        self.gpu_checkbox.setChecked(True)
        
        # 重置各个硬件选项到默认状态
        self.cpu_widget.checkbox.setChecked(False)
        self.cpu_widget.task_combo.setCurrentText("1")
        
        # 重置集显（如果检测到）
        if self.integrated_widget.checkbox.isEnabled():
            self.integrated_widget.checkbox.setChecked(True)
            self.integrated_widget.task_combo.setCurrentText("2")
        
        # 重置独显（如果检测到）
        if self.dedicated_widget.checkbox.isEnabled():
            self.dedicated_widget.checkbox.setChecked(True)
            self.dedicated_widget.task_combo.setCurrentText("3")
    
    def reset_settings(self):
        """重置GPU加速设置到默认状态"""
        # 重置GPU加速开关
        self.gpu_checkbox.setChecked(True)
        
        # 重置各个硬件选项到默认状态
        self.cpu_widget.checkbox.setChecked(False)
        self.cpu_widget.task_combo.setCurrentText("1")
        
        # 重置集显（如果检测到）
        if self.integrated_widget.checkbox.isEnabled():
            self.integrated_widget.checkbox.setChecked(True)
            self.integrated_widget.task_combo.setCurrentText("2")
        
        # 重置独显（如果检测到）
        if self.dedicated_widget.checkbox.isEnabled():
            self.dedicated_widget.checkbox.setChecked(True)
            self.dedicated_widget.task_combo.setCurrentText("3")


if __name__ == "__main__":
    # 测试GPU加速组件
    import sys
    from PyQt6.QtWidgets import QApplication, QMainWindow
    
    class TestWindow(QMainWindow):
        def __init__(self):
            super().__init__()
            self.setWindowTitle("GPU加速组件测试")
            self.setGeometry(100, 100, 600, 400)
            
            central_widget = QWidget()
            self.setCentralWidget(central_widget)
            
            layout = QVBoxLayout()
            
            # 添加GPU加速组件
            gpu_widget = GPUAccelerationWidget()
            layout.addWidget(gpu_widget)
            
            # 添加测试按钮
            from PyQt6.QtWidgets import QPushButton
            test_button = QPushButton("获取设置")
            test_button.clicked.connect(lambda: print(gpu_widget.get_acceleration_settings()))
            layout.addWidget(test_button)
            
            central_widget.setLayout(layout)
    
    app = QApplication(sys.argv)
    window = TestWindow()
    window.show()
    sys.exit(app.exec())